package com.tianhui.consignortwofei.update;

import android.content.Context;

import com.fgs.common.CommonModel;
import com.fgs.common.CommonResponse;
import com.fgs.common.api.CommonConfig;
import com.fgs.common.entity.UpdateInfo;
import com.fgs.common.entity.UpdateResultInfo;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.update.BaseUpdateStrategy;
import com.fgs.common.update.OnUpdateCallback;
import com.fgs.common.update.UpdateStrategy;
import com.fgs.common.utils.CommonUtil;
import com.fgs.common.utils.PackageUtil;
import com.tianhui.consignortwofei.api.AccountApiService;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fgs
 * @date 2021/5/28
 * @description 自动检查更新
 **/
public class ConsignorCheckUpdate extends BaseUpdateStrategy<UpdateResultInfo> {
    @Override
    public void checkUpdate(Context context, OnUpdateCallback onUpdateCallback) {
        String version = PackageUtil.getVersionName(CommonUtil.getContext());
        Map<String, String> map = new HashMap<>();
        map.put("version", version);
        map.put("terminal", "android");

        new CommonModel().subscribe(context, CommonConfig.getInstance().create(AccountApiService.class).checkUpdate(map), new ObserverResponseListener<CommonResponse<com.fgs.common.entity.UpdateInfo>>() {
            @Override
            public void onNext(CommonResponse<UpdateInfo> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    UpdateInfo updateInfo = commonResponse.getData();

                    UpdateResultInfo resultInfo = new UpdateResultInfo();
                    resultInfo.downloadUrl = updateInfo.download;
                    resultInfo.updateContent = updateInfo.description;
                    resultInfo.versionName = updateInfo.latestVersion;
                    resultInfo.isForceUpdate = updateInfo.needUpdate == 2;
                    resultInfo.updateType = UpdateStrategy.TYPE_AUTO;
                    if (updateInfo != null && onUpdateCallback != null) {
                        if (updateInfo.needUpdate == 0) { //不需要更新
                            if (onUpdateCallback != null) {
                                onUpdateCallback.withoutUpdate();
                            }
                        } else { //需要更新
                            showUpdateTip(context, resultInfo, onUpdateCallback);
                        }
                    }
                } else {
                    if (onUpdateCallback != null) {
                        onUpdateCallback.checkFailed();
                    }
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                if (onUpdateCallback != null) {
                    onUpdateCallback.checkFailed();
                }
            }
        });
    }

}
